package com.ltmonitor.web.controller.mobile;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.service.MapFixService;
import com.ltmonitor.util.Constants;
import com.ltmonitor.util.DateUtil;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.vo.PaginateResult;
import com.ltmonitor.vo.PointLatLng;
import com.ltmonitor.web.controller.GenericAction;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.OnlineUser;
import com.ltmonitor.web.vo.GpsData;

@Controller
@RequestMapping("/mobile")
public class VehicleListAction extends GenericAction {

	private static String REGISTER_KEY = "mobile_registerVehicleIds";

	@ResponseBody
	@RequestMapping("/registerVehicle.action")
	public JsonMessage register(String registerVehicleIds) {
		getVehicleIdMap().clear();
		if (StringUtil.isNullOrEmpty(registerVehicleIds) == false) {
			String[] vehicleIds = registerVehicleIds.split(",");
			for (String vehicleId : vehicleIds) {
				// vehicleIdList.add(Integer.parseInt(vehicleId));
				getVehicleIdMap().put(Integer.parseInt(vehicleId),
						Integer.parseInt(vehicleId));
			}
			this.LogOperation("移动端实时监控车辆，选择车辆数:" + vehicleIds.length);
		} else {
		}
		return json(true, "");
	}

	@ResponseBody
	@RequestMapping("/myVehicle.action")
	public JsonMessage myVehicle() {
		try {
			if (this.getOnlineUser() == null)
				return json(false, "会话过期，请重新登录");
			List<GpsData> result = new ArrayList<GpsData>();
			String queryId = "mobile.selectGpsData";
			Map params = this.getParams();
			params.put("userId", this.getOnlineUser().getEntityId());

			// params.put("depIdList", super.getAuthorizedDepIdList());
			// pageNo = pageNo == 0 ? 1 : pageNo;
			// pageSize = pageSize == 0 ? 10 : pageSize;

			List rs = super.queryService.query(queryId, params);

			if (rs.size() > 0) {
				for (Object obj : rs) {
					Map data = (Map) obj;
					GpsData gd = new GpsData();
					Integer vehicleId = (Integer) data.get("vehicleId");
					Map vehicleIdMap = this.getVehicleIdMap();
					if (vehicleIdMap.containsKey(vehicleId) == false)
						continue;
					gd.setVehicleId(vehicleId);
					gd.setPlateNo("" + data.get("plateNo"));
					gd.setDepName("" + data.get("depName1"));
					gd.setSimNo("" + data.get("simNo"));
					if (data.get("location") != null)
						gd.setLocation("" + data.get("location"));
					else
						gd.setLocation("");
					if (data.get("latitude") != null)
						gd.setLat(Double.parseDouble("" + data.get("latitude")));
					if (data.get("longitude") != null)
						gd.setLng(Double.parseDouble("" + data.get("longitude")));
					if (data.get("direction") != null)
						gd.setDirection((Integer) data.get("direction"));
					if (data.get("velocity") != null)
						gd.setSpeed(Double.parseDouble(""
								+ data.get("velocity")));
					String online = "" + data.get("online");
					gd.setOnline(online.equals("online") || online.equals("在线"));
					Date sendTime = (Date) data.get("sendTime");
					gd.setSendTime(DateUtil.toStringByFormat(sendTime,
							"yyyy-MM-dd HH:mm:ss"));
					result.add(gd);
				}
			}

			return json(true, result);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return json(false, e.getMessage());
		}
	}

	private Map<Integer, Integer> getVehicleIdMap() {
		Map<Integer, Integer> vehicleIdMap = (Map<Integer, Integer>) super
				.getFromSession(REGISTER_KEY);
		if (vehicleIdMap == null) {
			vehicleIdMap = new HashMap<Integer, Integer>();
			super.putSession(REGISTER_KEY, vehicleIdMap);
		}
		return vehicleIdMap;
	}

	@ResponseBody
	@RequestMapping("/vehicleList.action")
	public JsonMessage list(
			@RequestParam(required = false, defaultValue = "0") int pageNo,
			@RequestParam(required = false, defaultValue = "0") int pageSize,
			@RequestParam(required = false, defaultValue = "0") long depId) {
		try {
			OnlineUser user = this.getOnlineUser();
			if (user == null)
				return json(false, "会话已过期，请重新登录");
			List<GpsData> result = new ArrayList<GpsData>();
			String queryId = "selectGpsData";
			Map params = this.getParams();
			params.put("userId", user.getEntityId());

			if (depId == 0) {
				params.remove("depId");
			}
			// params.put("depIdList", super.getAuthorizedDepIdList());

			pageNo = pageNo == 0 ? 1 : pageNo;
			pageSize = pageSize == 0 ? 10 : pageSize;

			PaginateResult pr = super.queryService.queryByPagination(queryId,
					params, pageNo, pageSize);

			if (pr.getRows().size() > 0) {
				for (Object obj : pr.getRows()) {
					Map data = (Map) obj;
					GpsData gd = new GpsData();
					gd.setVehicleId((Integer) data.get("vehicleId"));
					gd.setPlateNo("" + data.get("plateNo"));
					gd.setDepName("" + data.get("depName1"));
					gd.setSimNo("" + data.get("simNo"));
					gd.setLocation("" + data.get("location"));
					if (data.get("latitude") != null)
						gd.setLat(Double.parseDouble("" + data.get("latitude")));
					if (data.get("longitude") != null)
						gd.setLng(Double.parseDouble("" + data.get("longitude")));
					if (data.get("direction") != null)
						gd.setDirection((Integer) data.get("direction"));
					if (data.get("speed") != null)
						gd.setSpeed((Double) data.get("speed"));
					String online = "" + data.get("online");
					gd.setOnline(online.equals("在线"));
					Date sendTime = (Date) data.get("sendTime");
					if (sendTime != null) {
						gd.setSendTime(DateUtil.toStringByFormat(sendTime,
								"yyyy-MM-dd HH:mm:ss"));
					}
					if (gd.getLat() > 0 && gd.getLng() > 0) {
						PointLatLng pl = MapFixService.fix(gd.getLat(),
								gd.getLng(), Constants.MAP_GOOGLE);
						gd.setLat(pl.getLat());
						gd.setLng(pl.getLng());
					}
					result.add(gd);
				}
			}

			this.LogOperation("移动端查询车辆");
			return json(true, result);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return json(false, e.getMessage());
		}
	}

}
